package com.dong.redis.config;

import com.dong.redis.service.RedisService;
import com.dong.redis.service.impl.RedisServiceImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: Redis 自动配置
 * @author: 陈瑞东
 * @create: 2022-12-09 15:20
 */
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {

    private RedisProperties redisProperties;

    public RedisAutoConfiguration(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }

    @Bean
    @ConditionalOnMissingBean
    JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(60000); //最大连接数
        jedisPoolConfig.setMaxIdle(300); //最大空闲连接数
        jedisPoolConfig.setTestOnBorrow(true);//<!-- 当调用borrow Object方法时，是否进行有效性检查 -->
        return jedisPoolConfig;
    }

    @Bean(name = "jedisPoolMap")
    @ConditionalOnMissingBean(name = "jedisPoolMap")
    public Map<Integer, JedisPool> jedisPoolMap(JedisPoolConfig jedisPoolConfig){
        Map<Integer, JedisPool> jedisPoolMap = new HashMap<>();

        String password = redisProperties.getPassword();

        for (Integer db : redisProperties.getDbs()) {
            if (password == null || "".equals(password)) {
                password = null;
            }
            JedisPool jedisPool = new JedisPool(jedisPoolConfig,redisProperties.getHost(),redisProperties.getPort(),
                    50000, password, db);
            jedisPoolMap.put(db, jedisPool);
        }

        return jedisPoolMap;
    }

    @Bean
    @ConditionalOnMissingBean
    public RedisService redisService(){
        return new RedisServiceImpl();
    }
}
